/**
 * 空校验 null、""、{}、[]都返回true
 */
export const isEmpty = (obj) => {
  if (typeof obj === 'string') {
    return !obj || obj.replace(/\s+/g, '') === ''
  } else {
    return !obj || JSON.stringify(obj) === '{}' || obj.length === 0
  }
}

/**
 * 非空校验
 */
export const isNotEmpty = (obj) => {
  return !isEmpty(obj)
}

/**
 * 对象复制
 * @param obj
 */
export const copy = (obj) => {
  if (isNotEmpty(obj)) {
    return JSON.parse(JSON.stringify(obj))
  }
  if (JSON.stringify(obj) === '{}') return {}
  if (Array.isArray(obj)) return []
}

/**
 * 使用递归将数组转为树形结构
 * 父ID属性为parent
 */
export const array2Tree = (array, parentId) => {
  if (isEmpty(array)) {
    return []
  }

  const result = []
  for (let i = 0; i < array.length; i++) {
    const c = array[i]
    // console.log(Number(c.parent), Number(parentId));
    if (Number(c.parent) === Number(parentId)) {
      result.push(c)

      // 递归查看当前节点对应的子节点
      const children = array2Tree(array, c.id)
      if (isNotEmpty(children)) {
        c.children = children
      }
    }
  }
  return result
}

/**
 * 随机生成[len]长度的[radix]进制数
 * @param len
 * @param radix 默认62
 * @returns {string}
 */
export const uuid = (len, radix = 62) => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
  const uuid = []
  radix = radix || chars.length

  for (let i = 0; i < len; i++) {
    uuid[i] = chars[0 | (Math.random() * radix)]
  }

  return uuid.join('')
}
